<template>
  <div class="vc-checkerboard"></div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue'

const _checkBoardCache: any = {}

export default defineComponent({
  name: 'CheckBoard',
  props: {
    size: {
      type: Number,
      default: 8
    },
    white: {
      type: String,
      default: '#fff'
    },
    grey: {
      type: String,
      default: '#e6e6e6'
    }
  },
  setup(props) {
    /**
     * get base 64 data by canvas
     *
     * @param {String} c1 hex color
     * @param {String} c2 hex color
     * @param {Number} size
     */
    const renderCheckBoard = (c1: string, c2: string, size: number) => {
      // Dont Render On Server
      if (typeof document === 'undefined') {
        return null
      }
      const canvas = document.createElement('canvas')
      canvas.width = canvas.height = size * 2
      const ctx = canvas.getContext('2d')
      // If no context can be found, return early.
      if (!ctx) {
        return null
      }
      ctx.fillStyle = c1
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      ctx.fillStyle = c2
      ctx.fillRect(0, 0, size, size)
      ctx.translate(size, size)
      ctx.fillRect(0, 0, size, size)
      return canvas.toDataURL()
    }

    /**
     * get checkboard base data and cache
     *
     * @param {String} c1 hex color
     * @param {String} c2 hex color
     * @param {Number} size
     */
    const getCheckBoard = (c1: string, c2: string, size: number) => {
      const key = c1 + ',' + c2 + ',' + size

      if (_checkBoardCache[key]) {
        return _checkBoardCache[key]
      } else {
        const checkBoard = renderCheckBoard(c1, c2, size)
        _checkBoardCache[key] = checkBoard
        return checkBoard
      }
    }

    return {
      bgStyle: computed(() => {
        return {
          'background-image': 'url(' + getCheckBoard(props.white, props.grey, props.size) + ')'
        }
      })
    }
  }
})
</script>